<template>
  <canvas ref="canvas" style="width: 100vw; height: 100vh"></canvas>
</template>

<script setup lang="ts">
import * as THREE from 'three'
const canvas = ref(null) as any

function main() {
  const renderer = new THREE.WebGLRenderer({ canvas: canvas.value })

  const fov = 40
  const aspect = 2 // the canvas default
  const near = 0.4
  const far = 1000
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far) // 摄像机
  camera.position.set(0, 50, 0)
  camera.up.set(0, 0, 1)
  camera.lookAt(0, 0, 0)

  const scene = new THREE.Scene() // 场景

  const color = 0xffffff
  const intensity = 3
  const light = new THREE.PointLight(color, intensity)
  scene.add(light) // 关源

  const objects = [] as any

  const radius = 1
  const widthSegments = 6
  const heightSegments = 6
  const sphereGeometry = new THREE.SphereGeometry(
    radius,
    widthSegments,
    heightSegments,
  )
  const earthMaterial = new THREE.MeshPhongMaterial({
    color: 0x2233ff,
    emissive: 0x112244,
  })

  const moonMaterial = new THREE.MeshPhongMaterial({
    color: 0x888888,
    emissive: 0x222222,
  })

  const solarSystem = new THREE.Object3D()
  const earthOrbit = new THREE.Object3D()
  earthOrbit.position.x = 10
  const moonOrbit = new THREE.Object3D()
  const sunMaterial = new THREE.MeshPhongMaterial({ emissive: 0x44aa88 })

  const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial) // 网络

  const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial)
  sunMesh.scale.set(5, 5, 5)

  const moonMesh = new THREE.Mesh(sphereGeometry, moonMaterial)
  moonMesh.scale.set(0.5, 0.5, 0.5)
  moonOrbit.position.x = 2
  moonOrbit.add(moonMesh) // 先给3d moonOrbit 添加上网格
  earthOrbit.add(moonOrbit) // 把 moonOrbit作为 自己的孩子添加

  earthOrbit.add(earthMesh) // 给earthOrbit 添加网格

  objects.push(earthOrbit)
  objects.push(solarSystem)
  objects.push(moonMesh)
  solarSystem.add(earthOrbit)
  solarSystem.add(sunMesh)
  scene.add(solarSystem) // 核心

  function resizeRendererToDisplaySize(renderer: any) {
    const canvas = renderer.domElement
    const width = canvas.clientWidth
    const height = canvas.clientHeight
    const needResize = canvas.width !== width || canvas.height !== height
    if (needResize) {
      renderer.setSize(width, height, false)
    }
    return needResize
  }

  function render(time: any) {
    time *= 0.001

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement
      camera.aspect = canvas.clientWidth / canvas.clientHeight
      camera.updateProjectionMatrix()
    }

    objects.forEach((obj: any) => {
      obj.rotation.y = time
    })

    renderer.render(scene, camera)

    requestAnimationFrame(render)
  }

  requestAnimationFrame(render)
}

//

onMounted(() => {
  console.log(canvas)
  main()
})
</script>

<style lang="scss" scoped></style>
